<template>
  <div class="register-container">
    <div class="register-box">
      <h1 class="title">用户注册</h1>
      <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="rules"
          class="register-form"
      >
        <el-form-item prop="username">
          <el-input
              v-model="registerForm.username"
              placeholder="用户名"
              size="large"
          >
            <template #prefix>
              <el-icon>
                <User/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="realName">
          <el-input
              v-model="registerForm.realName"
              placeholder="真实姓名"
              size="large"
          >
            <template #prefix>
              <el-icon>
                <User/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="email">
          <el-input
              v-model="registerForm.email"
              placeholder="电子邮箱"
              size="large"
          >
            <template #prefix>
              <el-icon>
                <Message/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="phone">
          <el-input
              v-model="registerForm.phone"
              placeholder="手机号码"
              size="large"
          >
            <template #prefix>
              <el-icon>
                <Phone/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="registerForm.password"
              placeholder="密码"
              show-password
              size="large"
              type="password"
          >
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              placeholder="确认密码"
              show-password
              size="large"
              type="password"
          >
            <template #prefix>
              <el-icon>
                <Lock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="agreement">
          <el-checkbox v-model="registerForm.agreement">
            我已阅读并同意
            <el-button link type="primary" @click="showAgreement">《用户协议》</el-button>
          </el-checkbox>
        </el-form-item>

        <div class="form-actions">
          <el-button
              :loading="loading"
              class="submit-button"
              size="large"
              type="primary"
              @click="handleSubmit"
          >
            注册
          </el-button>
          <div class="login-link">
            已有账号？
            <router-link to="/login">返回登录</router-link>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue';
import {ElMessage} from 'element-plus';
import {useRouter} from 'vue-router';
import axios from 'axios';
import {Lock, Message, Phone, User} from '@element-plus/icons-vue';

const router = useRouter();
const registerFormRef = ref();

// 注册表单数据
const registerForm = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  agreement: false
});

// 表单验证规则
const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur'}
  ],
  realName: [
    {required: true, message: '请输入真实姓名', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入电子邮箱', trigger: 'blur'},
    {type: 'email', message: '请输入有效的电子邮箱地址', trigger: 'blur'}
  ],
  phone: [
    {pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认密码', trigger: 'blur'},
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  agreement: [
    {
      validator: (rule: any, value: boolean, callback: Function) => {
        if (!value) {
          callback(new Error('请阅读并同意用户协议'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
};

// 加载状态
const loading = ref(false);

// 处理注册提交
const handleSubmit = async () => {
  if (!registerFormRef.value) return;

  try {
    await registerFormRef.value.validate();
    loading.value = true;

    // 发送注册请求
    const response = await axios.post('/api/users/register', {
      username: registerForm.username,
      realName: registerForm.realName,
      email: registerForm.email,
      phone: registerForm.phone,
      password: registerForm.password
    });

    ElMessage.success('注册成功');

    // 跳转到登录页，并传递用户名参数用于自动填充
    router.push({
      path: '/login',
      query: {username: registerForm.username}
    });
  } catch (error: any) {
    console.error('注册失败:', error);

    // 显示错误信息
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message);
    } else {
      ElMessage.error('注册失败，请稍后重试');
    }
  } finally {
    loading.value = false;
  }
};

// 显示用户协议
const showAgreement = () => {
  ElMessage.info('用户协议内容将在此显示');
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
  background-image: url('');
}

.register-box {
  width: 400px;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.title {
  text-align: center;
  color: #409eff;
  margin-bottom: 30px;
  font-size: 28px;
}

.register-form {
  width: 100%;
}

.form-actions {
  margin-top: 20px;
}

.submit-button {
  width: 100%;
  margin-bottom: 16px;
}

.login-link {
  text-align: center;
  margin-top: 16px;
}

@media screen and (max-width: 576px) {
  .register-box {
    width: 90%;
    padding: 20px;
  }
}
</style> 